/**
 * @author Gabriele Cerfoglio
 * @author Fatima Chegini
 * @author Nicolas Latorre
 * @author Giuseppe Mendola
 */
package sa4.persistence

import org.squeryl.KeyedEntity
import org.squeryl.SessionFactory
import org.squeryl.Session
import org.squeryl.adapters.H2Adapter
import scala.util.matching.Regex
import org.squeryl.adapters.H2Adapter
import java.sql.Timestamp
import java.sql.Date
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.dsl.ast.LogicalBoolean
import org.squeryl.annotations.OptionType

//settings MyShop
class Client(val name: String, val email: String, val pass: String) extends KeyedEntity[Long] {
  val id = 0L

  def login(name: String, pass: String) {
    from(Shop.clients)(a =>
      where(a.name === name and a.pass === pass)
        select (a))
  }

}
class Product(val name: String, val cost: Int) extends KeyedEntity[Long] {
  val id = 0L
}
class Cart(val client: Long, val product: Long) extends KeyedEntity[Long] {
  def this() = this(0, 0)
  val id = 0L
}

class Account(val name: String, val balance: Int) extends KeyedEntity[Long] {
  def this() = this("", 0)
  val id = 0L
}

class Movement(val name: String, val amount: Int, val date: java.util.Date, val action: String) {
  def this() = this("", 0, new java.util.Date, "")
  val id = 0L
}

object Shop extends org.squeryl.Schema {
  val clients = table[Client]
  val products = table[Product]
  val carts = table[Cart]
}

object Bank extends org.squeryl.Schema {
  val accounts = table[Account]
  val movements = table[Movement]
}

class Persistence {
  def getAccounts = {
    transaction {
      for (a <- Bank.accounts)
        yield <tr><td>{ a.name }</td><td>{ a.balance }</td></tr>
    }
  }

  def getMouvements = {
    transaction {
      for (a <- Bank.movements)
        yield <tr><td>{ a.name }</td><td>{ a.amount }</td><td>{ a.date }</td><td>{ a.action }</td></tr>
    }
  }

  def newAccount(name: String, balance: String) = {
    val b = balance.toInt
    transaction {
      Bank.accounts.insert(new Account(name, b))
      Bank.movements.insert(new Movement(name, b, new java.util.Date, "Update"))
    }
  }

  def deleteAccount(name: String) = {
    transaction {
      Bank.accounts.deleteWhere(a => a.name === name)
    }
  }

  def updateAccount(name: String, balance: String) = {
    val b = balance.toInt
    transaction {
      update(Bank.accounts)(a =>
        where(a.name === name)
          set (a.balance := b))
      Bank.movements.insert(new Movement(name, b, new java.util.Date, "Update"))
    }
  }

}